<?php

declare(strict_types=1);

namespace App\ChannelCode\Logic;

use Hyperf\Di\Annotation\Inject;
use App\ChannelCode\Service\ChannelCodeGroupService;
use App\ChannelCode\Service\ChannelCodeService;
use App\WorkContact\Service\WorkContactTagService;
use App\WorkContact\Service\WorkContactEmployeeService;
use App\ChannelCode\Constants\AutoAddFriend;
use App\ChannelCode\Constants\Type;

/**
 *
 * Class IndexLogic
 */
class IndexLogic
{

    /**
     * @Inject
     * @var ChannelCodeService
     */
    protected $channelCodeService;

    /**
     * @Inject
     * @var WorkContactTagService
     */
    protected $workContactTagService;

    /**
     * @Inject
     * @var ChannelCodeGroupService
     */
    protected $channelCodeGroupService;

    /**
     * /**
     * 客户-员工关联表.
     * @Inject
     * @var WorkContactEmployeeService
     */
    protected $WorkContactEmployeeService;


    /**
     * 参数.
     * @var array
     */
    private $params;


    /**
     * @return array
     */
    public function getOne()
    {
        return $data ?? [];
    }

    /**
     * 处理查询信息.
     * @return array
     */
    private function handleInfo()
    {
        $where = [];
        //企业id
        //网关拿的企业ID
        $where['corp_id'] = $this->params['corpId'];
        $where['is_deleted'] = 0;
        //活码名称搜索
        if (!empty($this->params['name'])) {
            $where[] = ['name', 'like', '%' . $this->params['name'] . '%'];
        }
        //活码类型搜索
        if (!empty($this->params['type'])) {
            $where['type'] = $this->params['type'];
        }
        //分组搜索
        if (is_numeric($this->params['groupId'])) {
            $where['group_id'] = $this->params['groupId'];
        }

        $columns = [
            'id',
            'group_id',
            'name',
            'qrcode_url',
            'auto_add_friend',
            'tags',
            'type',
        ];
        $options = [
            'orderByRaw' => 'update_time desc',
            'perPage' => isset($this->params['size']) ? (int)$this->params['size'] : 20,
            'page' => isset($this->params['current']) ? (int)$this->params['current'] : 1,
            'pageName' => 'page',
        ];

        return [
            'where' => $where,
            'columns' => $columns,
            'options' => $options,
        ];
    }

    /**
     * 列表分页
     * @param $params
     * @return array
     */
    public function getListPage($params)
    {
        $this->params = $params;
        //处理查询信息
        $handleParams = $this->handleInfo();
        if (empty($handleParams)) {
            return [
                'size' => 10,
                'total' => 0,
                'pages' => 0,
                'current' => 0,
                'records' => [],
            ];
        }

        //查询列表
        $info = $this->channelCodeService->getChannelCodeList($handleParams['where'], $handleParams['columns'], $handleParams['options']);

        if (empty($info['data'])) {
            return [
                'size' => 10,
                'total' => 0,
                'pages' => 0,
                'current' => 0,
                'records' => [],
            ];
        }

        $groupIds = array_unique(array_column($info['data'], 'groupId'));
        //根据分组id查询分组名
        $groupInfo = $this->getGroup($groupIds);

        $ids = array_column($info['data'], 'id');
        //根据id查询客户数 预留
        $contact = $this->getContact($ids);

        $new_data = [];
        //拼接数据
        foreach ($info['data'] as $k => $val) {
            $new_data[$k]['channelCodeId'] = $val['id'] ?? '';
            $new_data[$k]['groupName'] = '';
            if (isset($groupInfo[$val['groupId']])) {
                $new_data[$k]['groupName'] = $groupInfo[$val['groupId']]['name'] ?? '';
            }

            if (!empty($val['tags'])) {
                $tagIds = json_decode($val['tags'], true);
                if(!empty($tagIds) and is_array($tagIds)){
                    $new_data[$k]['tags'] = $this->getTagInfo($tagIds);
                }else{
                    $new_data[$k]['tags'] = [];
                }
            }

            $new_data[$k]['contactNum'] = 0;
            if (isset($contact['channelCode-' . $val['id']])) {
                $new_data[$k]['contactNum'] = count($contact['channelCode-' . $val['id']]['contact']);
            }

            if ($val['autoAddFriend'] != 0) {
                $new_data[$k]['autoAddFriend'] = AutoAddFriend::getMessage($val['autoAddFriend']);
            }

            $new_data[$k]['qrcodeUrl'] = empty($val['qrcodeUrl']) ? '' : file_full_url($val['qrcodeUrl']);
            $new_data[$k]['type'] = Type::getMessage($val['type']);

            $new_data[$k]['user'] = '';
            $new_data[$k]['name'] = $val['name'] ?? '';
        }

        return [
            'size' => isset($info['per_page']) ? $info['per_page'] : 20,
            'total' => isset($info['total']) ? $info['total'] : 0,
            'pages' => isset($info['last_page']) ? $info['last_page'] : 0,
            'current' => $this->params['current'],
            'records' => $new_data ?? [],
        ];
    }

    /**
     * 查询分组信息.
     * @param $groupIds
     * @return array
     */
    private function getGroup($groupIds)
    {
        $res = $this->channelCodeGroupService->getChannelCodeGroupsById($groupIds);
        if (empty($res)) {
            return [];
        }

        return array_column($res, null, 'id');
    }

    /**
     * 获取客户数.
     * @param $ids
     * @return array
     */
    private function getContact($ids)
    {
        $channelCodeIds = [];
        foreach ($ids as $val) {
            $channelCodeIds[] = 'channelCode-' . $val;
        }

        //查询客户数
        $contactEmployee = $this->WorkContactEmployeeService->getWorkContactEmployeesByStates($channelCodeIds, ['contact_id', 'state']);
        if (empty($contactEmployee)) {
            return [];
        }

        $contact = [];
        foreach ($contactEmployee as &$val) {
            if (isset($contact[$val['state']])) {
                $contact[$val['state']]['contact'][] = $val['contactId'];
            } else {
                $tmp = [];
                $tmp['contact'][] = $val['contactId'] ?? '';

                $contact[$val['state']] = $tmp;
            }
        }

        return $contact;
    }


    /**
     * 获取标签信息.
     * @param $tagIds
     * @return array
     */
    private function getTagInfo($tagIds)
    {
        if(!is_array($tagIds)) return [];
        $res = $this->workContactTagService->getWorkContactTagsById($tagIds);
        if (empty($res)) {
            return [];
        }

        return array_column($res, 'name');
    }

}
